import { calendarPriceInquiry, confirmOrder, createOrder } from '../../../api/home/index'
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';

let priceDataList = []

Page({
  /**
   * 页面的初始数据
   */
  data: {
    prodId: '', // 产品id
    prodName: '', // 产品name
    formData: {
      calendarPriceId: '',
      prodId: '', // 产品id
      orderToken: '', // 唯一token，提交订单需要
      userId: '', // 下单用户userId
      linkName: '', //联系人姓名  
      linkCardNo: '', //联系人证件号
      linkPhone: '', //联系人手机号
      count: 0, //已售数量
      remark: '', //备注
      playStartDate: '', //游玩开始时间
      playEndDate: '', //游玩结束时间
      tourismName: '', //景区名称
      tourismId: '', //景区id
      price: 0, //总价格
      realPrice: 0, //实际支付金额
      payType: '1', //支付方式，0：支付宝，1：微信
      disPrice: 0,  //优惠价格
      orderPlays: [
        {
          playName: '', //游玩人姓名
          playCardNo: '', //游玩人证件号
          playPhone: '',  //游玩人手机号
          playCardType: '0', //游玩人证件类型
          prodId: '', //产品id
          prodName: '' //产品名称
        }
      ]
    },
    date: '',
    show: false,
    salePrice: 0,
    defaultDate: [],
    username: '',
    phone: '',
    message: '',
    checked: false,
    value1: 0,
    option1: [
      { text: '明细', value: 0 },
    ],
    showPrice: false,
    productName: '',
    showNoiceContent: false, 
    orderDesc: '', // 预订须知
    phoneError: '',
    minDate: new Date(2023, 0, 1).getTime(),
    maxDate: new Date(2023, 5, 30).getTime(),
    // minDate: new Date(2023, 0, 1).getTime(),
    // maxDate: new Date(2023, 0, 31).getTime(),
    priceList: [],
    ticketPrices: [],
    snapupPrices:[],
    monthTicket:0, //是否为期票
    appointment:'',//期票有效期
    wechatPay: {
      timeStamp: '',
      nonceStr: '',
      package: '',
      signType: '',
      paySign: '',
    }
  },

  // 调用微信支付
  weChatPay () {
		const that = this
		console.log(that.data.wechatPay)
    wx.requestPayment({
      timeStamp: that.data.wechatPay.timeStamp,
      nonceStr: that.data.wechatPay.nonceStr,
      package: that.data.wechatPay.package,
      signType: that.data.wechatPay.signType,
      paySign: that.data.wechatPay.paySign,
      success: function(res) {
        console.log('支付成功')
        Toast.loading({
          message: '加载中...',
          forbidClick: true,
        });
        wx.navigateBack({
          delta: 2,
        })
        // that.orderQuery()
      },
      fail: function(error) {
				console.log(error)
        wx.showToast({
          icon: 'error',
          title: '支付失败'
        })
      }
    })
  },

  onChange(event) {
    // console.log(event.detail);
    if(event.detail > 9) {
      wx.showToast({
        title: '最多只能选9张!',
        icon: 'error',
        duration: 2000
      })
      return
    }
    this.setData({
      'formData.count': event.detail
    })
    console.log(this.data.formData.count)
  },

  onChange1() {
    const { checked } = this.data
    this.setData({
      checked: !checked
    })
  },

  onChange2() {
    this.onChange1()
  },

  selectMoreTime() {
    this.setData({
      show: true
    })
  },

  changeName(e) {
    // console.log(e)
    const { index } = e.currentTarget.dataset
    const { orderPlays } = this.data.formData
    orderPlays[index].playName = e.detail
    orderPlays[index].prodId = Number(this.data.prodId)
    orderPlays[index].prodName = this.data.prodName

    if(index == 0) {
      this.setData({
        'formData.linkName': wx.getStorageSync('linkName')
      })
    }
  },

  changeIdCard(e) {
    const { index } = e.currentTarget.dataset
    const { orderPlays } = this.data.formData
    orderPlays[index].playCardNo = e.detail
    if(index == 0) {
      this.setData({
        'formData.linkCardNo': wx.getStorageSync('linkCardNo')
      })
    }
  },

  changePhone(e) {
    // console.log(e.detail)
    const { index } = e.currentTarget.dataset
    const { orderPlays } = this.data.formData
    orderPlays[index].playPhone = e.detail
    if(index == 0) {
      this.setData({
        'formData.linkPhone': e.detail
      })
    }
  },

  changeRemark(e) {
    this.setData({
      'formData.remark': e.detail
    })
  },

  // 添加门票
  addTiket(e) {
    console.log(e)
    console.log('增加门票===')
    const { orderPlays } = this.data.formData
    orderPlays.push({
      playName: '',
      playCardNo: '',
      playPhone: '',
      playCardType: '0',
      prodId: '',
      prodName: ''
    })
    this.setData({
      'formData.orderPlays': orderPlays,
    })
  },

  // 减少门票
  reduceTiket(e) {
    console.log('减少门票===')
    const { orderPlays } = this.data.formData
    const index = orderPlays.length - 1
    orderPlays.splice(index, 1)
    this.setData({
      'formData.orderPlays': orderPlays
    })
  },

  onDisplay() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },

  onConfirm(event) {
    console.log(event)
    this.onselect(event)
    const { date1 } = this.data
    this.setData({
      show: false,
      date: date1
    });
  },

  onselect(e) {
    console.log(e)
    let date = new Date(e.detail)
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    m = m < 10 ? ('0' + m) : m
    let d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    const time =  y + '-' + m + '-' + d;
    console.log(time)// 输出例：2021-06-23
    const selectObj = this.data.priceList.filter(item => {
      return item.date === time
    })
    console.log(selectObj)
    const { formData } = this.data
    console.log(formData.orderPlays.length)
    this.setData({
      date1: time,
      // 'formData.price': selectObj.salePrice,
      'formData.price': formData.orderPlays.length * (selectObj[0].salePrice * 1000)/1000,
      'formData.realPrice': formData.orderPlays.length * (selectObj[0].salePrice * 1000)/1000,
      'formData.playStartDate': selectObj[0].date,
      'formData.playEndDate': selectObj[0].date,
      'formData.calendarPriceId': selectObj[0].id,
      salePrice: selectObj[0].salePrice
    })
    console.log(formData.price)
    console.log(formData.realPrice)
    console.log(this.data.formData)
  },

  openDetail() {
    this.setData({
      showPrice: true
    })
  },

  onClosePrice() {
    this.setData({
      showPrice: false
    })
  },
  isIdcard(value) {
    var sId = value;
    if (sId.length == 15) {
      if(!/^\d{14}(\d|x)$/i.test(sId)){
        return false;
      } else  {
          sId=sId.substr(0,6)+'19'+sId.substr(6,9);
          sId+= getVCode(sId);
      }
    }
    function getVCode(CardNo17) {
      var Wi = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);
      var Ai = new Array('1','0','X','9','8','7','6','5','4','3','2');
      var cardNoSum = 0;
      for (var i=0; i<CardNo17.length; i++)cardNoSum+=CardNo17.charAt(i)*Wi[i];
      var seq = cardNoSum%11;
      return Ai[seq];
    }
    var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"} ;

    var iSum=0 ;
    var info="" ;
    if(!/^\d{17}(\d|x)$/i.test(sId)){
      return false;
    }
    sId=sId.replace(/x$/i,"a"); 
    if(aCity[parseInt(sId.substr(0,2))]==null){ 
      return false;
    }
    var sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); 
    var d=new Date(sBirthday.replace(/-/g,"/")) ;
    if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate())){
      return false; 
    }
    for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ;
    if(iSum%11!=1){
      return false; 
    }
    return true;
  },

  // 提交订单(新)
  async goReserve() {
    wx.navigateTo({
      url: '/subpackages/pages/views/tour/tour',
    })
    const regLinkMan = /^([\p{Unified_Ideograph}·]){2,20}$/u
    const regPhone = /^[1][3,4,5,6,7,8][0-9]{9}$/

    const { playStartDate, orderPlays } = this.data.formData
    const { prodId } = this.data
    const that = this
    this.setData({
      'formData.count': orderPlays.length
    })
    // that.setData({
    //   wechatPay: res.data
    // })
    // this.weChatPay() // 调用微信支付
    if(!playStartDate) {
      wx.showToast({
        title: `日期不能为空`,
        icon: 'error',
        duration: 1000
      })
      return
    }

    for(let i=0; i< orderPlays.length; i++) {
      let playName = orderPlays[i].playName
      let playCardNo = orderPlays[i].playCardNo
      let playPhone = orderPlays[i].playPhone
      if(!playName) {
        wx.showToast({
          title: `姓名不能为空`,
          icon: 'error',
          duration: 1000
        })
        return
      }
      if(!playCardNo) {
        wx.showToast({
          title: `身份证不能为空`,
          icon: 'error',
          duration: 1000
        })
        return
      }
      if(!playPhone) {
        wx.showToast({
          title: `手机号不能为空`,
          icon: 'error',
          duration: 1000
        })
        return
      }
      if(!regLinkMan.test(playName)) {
        wx.showToast({
          title: `姓名格式有误`,
          icon: 'error',
          duration: 1000
        })
        return
      }
      if(!this.isIdcard(playCardNo)) {
        wx.showToast({
          title: `身份证格式有误`,
          icon: 'error',
          duration: 1000
        })
        return
      }
      if(!regPhone.test(playPhone)) {
        wx.showToast({
          title: `手机号格式有误`,
          icon: 'error',
          duration: 1000
        })
        return
      }
    }

    const userid = wx.getStorageSync('openid') // 'oThCR5fmrhn2jQ4bmu4cG8Za2ge8' //  wx.getStorageSync('openid')
    const data = {
      prodId,
      count: orderPlays.length,
      userId: userid,
      calendarPriceId: this.data.formData.calendarPriceId
    }
    this.setData({
      'formData.realPrice': this.data.formData.price * this.data.formData.count
    })
    console.log('提交订单入参===', this.data.formData)
    let res = await confirmOrder(data)
		console.log('创建订单成功===', res)
		this.setData({
			'formData.orderToken': res.data.orderToken
		})
    if(res && res.code === 200) {
      createOrder(this.data.formData).then(res1 => {
        if(res1.code === 200) {
          console.log('提交订单成功===', res1)
          wx.navigateTo({
            url: `/pages/views/orderDetail/orderDetail?orderId=${res1.data}`
          })
        } else {
          Toast('存在未支付的订单，请先处理该未支付的订单再重新下单！')
        }
      }).catch(error => {
        console.log('返回的错误')
        console.log(error)
      })
      
    } else {
      console.log('err===')
      Toast('存在未支付的订单，请先处理该未支付的订单再重新下单！')
    }
  },

  // 预订须知
  noticeReserve() {
    this.setData({
      showNoiceContent: true
    })
  },

  getPriceList() {
    this.setData({
      formatter(day) {
        let year = day.date.getFullYear()
        let month = day.date.getMonth() + 1;
        month = month < 10 ? ('0' + month) : month
        let date = day.date.getDate();
        date = date < 10 ? ('0' + date) : date
        let singleDay = `${year}-${month}-${date}`
        // console.log(singleDay) // 日历价格
        const priceDataList = wx.getStorageSync('priceDataList')
        console.log('初始化priceDataList===', priceDataList)
        priceDataList.forEach(item => {
          if(item.date === singleDay) {
            day.bottomInfo = `¥${item.salePrice}`
          }
        })
        if(!day.bottomInfo) {
          day.type = 'disabled'
        }
        return day;
      }
    })
  },

  onLoad() {
    const options = {
      id: '1',
      count: '81',
      newPrice: '80.00',
      title: '门票大明边城-成人票',
      tourismId: '1',
      tourismName: '大明边城'
    }
    const { id, title, newPrice, count, tourismId, tourismName } = options
    const userid = wx.getStorageSync('openid')
    this.setData({
      prodId: Number(id),
      prodName: title,
      'formData.prodId': Number(id),
      'formData.userId': userid,
      'formData.tourismName': tourismName,
      'formData.tourismId': Number(tourismId)
    })

    calendarPriceInquiry(id).then(res => {
      console.log(res)
      if(res.code === 200) {
        this.setData({
          priceList: res.data
        })
        console.log(this.data.priceList)
        this.setData({
          formatter(day) {
            let year = day.date.getFullYear()
            let month = day.date.getMonth() + 1;
            month = month < 10 ? ('0' + month) : month
            let date = day.date.getDate();
            date = date < 10 ? ('0' + date) : date
            let singleDay = `${year}-${month}-${date}`
            // console.log(singleDay) // 日历价格
            res.data.forEach(item => {
              if(item.date === singleDay) {
                day.bottomInfo = `¥${item.salePrice}`
                day.topInfo = item.num > 10 ? `>10张` : `${item.num}张`
              }
            })
            if(!day.bottomInfo) {
              day.type = 'disabled'
            }
            return day;
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})